package jmine.tec.web.front.pages.form;

import java.util.List;

import jmine.tec.web.wicket.pages.form.FormType;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

/**
 * Abstract base to use with handled forms
 * 
 * @author israel.crisanto
 */
public abstract class AbstractHandledFormPanel extends Panel {

    private FormType defaultFormType;

    /**
     * {@inheritDoc}
     */
    protected abstract List<Component> createFormComponents();

    /**
     * @param id markup id
     * @param panelModel model
     * @param formType form type
     */
    public AbstractHandledFormPanel(String id, IModel<?> panelModel, FormType formType) {
        super(id, panelModel);
        this.defaultFormType = formType;
        this.renderFormComponents();
    }

    /**
     * Render form components
     */
    protected void renderFormComponents() {
        List<Component> components = this.createFormComponents();

        for (Component component : components) {
            this.add(this.disableComponentIfNeeded(component));
        }
    }

    /**
     * Disable components if in view mode
     * 
     * @param component component
     * @return component
     */
    private Component disableComponentIfNeeded(Component component) {
        boolean disableField = this.defaultFormType.isView();

        AttributeModifier ro = new AttributeModifier("readonly", disableField, new Model<String>("readonly"));
        AttributeModifier disabled = new AttributeModifier("disabled", disableField, new Model<String>("disabled"));

        if (component.isEnabled()) {
            component.add(ro).add(disabled).setEnabled(!disableField);
        }

        return component;
    }
}
